package pri.zxx.webdemo.controllers;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import pri.zxx.webdemo.config.ExPrint;
import pri.zxx.webdemo.config.FilePathConstant;
import pri.zxx.webdemo.entity.vo.ResultData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Twilight
 * @desc
 * @createTime 2020-05-16-18:15
 */
@RestController
@Tag(name =  "LEARN_DEMO-文件操作接口组")
@RequestMapping(value = "/files")
@Slf4j
public class FileOpeController {

    /**
     * 文件上传具体实现方法;
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public ResultData handleFileUpload(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                File picPath = new File(FilePathConstant.MYFILES);
                if (!picPath.exists()) {
                    picPath.mkdirs();
                }
                File destination = new File(FilePathConstant.MYFILES + file.getOriginalFilename());
                if (!destination.exists()) {
                    destination.createNewFile();
                }
                log.warn("canWrite :" + destination.canWrite());
                log.warn("canRead:" + destination.canRead());
                log.warn("canExecute:" + destination.canExecute());
                log.warn("path:" + destination.getPath());
                FileUtils.copyToFile(file.getInputStream(), destination);
//                file.transferTo(destination);
            } catch (IOException e) {
                String print = ExPrint.print(e);
                log.error("上传文件异常 {}", print);
                return ResultData.fail("上传文件异常" + print);
            }
            return ResultData.success("上传成功");
        } else {
            return ResultData.fail("上传失败，因为文件是空的.");
        }
    }


    @Operation(summary = "返回图片")
    @GetMapping(value = "/one", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public byte[] getImage() throws IOException {
        File file = new File(FilePathConstant.MYFILES + "QQ图片20180927181736.png");
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = IOUtils.toByteArray(inputStream);
        inputStream.close();
        return bytes;
    }

    @Operation(summary = "返回图片列表")
    @GetMapping(value = "/many")
    public ResultData getImages() throws IOException {
        File file = new File(FilePathConstant.MYFILES + "辐射4年度版1920x1080壁纸_彼岸图网.jpg");
        File file2 = new File(FilePathConstant.MYFILES + "夜晚 星星 星空 梦幻 4K壁纸_彼岸图网.jpg");
        byte[] bytes = FileUtils.readFileToByteArray(file);
        byte[] bytes2 = FileUtils.readFileToByteArray(file2);
        String s = Base64.getEncoder().encodeToString(bytes);
        String s2 = Base64.getEncoder().encodeToString(bytes2);
        Map<String, String> bufferedImages = new HashMap<>();
        bufferedImages.put("img", s);
        bufferedImages.put("img2", s2);
        return ResultData.success(bufferedImages);
    }

    /**
     * nio 文件上传具体实现方法;
     *
     * @param file
     * @return
     */
    @PostMapping("nioUpload")
    @Operation(summary = "nio文件上传")
    public ResultData nioFileUp(MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            Path path = Paths.get(FilePathConstant.MYFILES, file.getOriginalFilename());
            Files.deleteIfExists(path);
            long copy;
            try {
                copy = Files.copy(file.getInputStream(), path);
                log.warn("copy:{}m", copy / (1024 * 1024));
                return ResultData.success("上传成功");
            } catch (IOException e) {
                log.error("上传文件失败{}", ExPrint.print(e));
                return ResultData.fail("上传失败");
            }
        } else {
            return ResultData.fail("上传失败，因为文件是空的.");
        }
    }
}

